﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Pop3;

namespace TPTecnicas.MessageProcessor.Common
{
	public class Utils
	{
		public static void SaveMailAttachment(System.Net.Mail.Attachment attachment)
		{
			byte[] allBytes = new byte[attachment.ContentStream.Length];
			int bytesRead = attachment.ContentStream.Read(allBytes, 0, (int)attachment.ContentStream.Length);

			string destinationFile = attachment.Name;

			BinaryWriter writer = new BinaryWriter(new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None));
			writer.Write(allBytes);
			writer.Close();
		}


		public static Mail RxMessageToMail(Pop3.RxMailMessage rxMail)
		{
				Mail mail = new Mail();

				//TODO hacer un datamapper o ver si se persiste el mail y hacer una POCO
				if (!String.IsNullOrEmpty(rxMail.Body))
					mail.Body = rxMail.Body;
				else if (!String.IsNullOrEmpty(rxMail.Entities[0].Body))
					mail.Body = rxMail.Entities[0].Body;
				else
					mail.Body = rxMail.Entities[1].Body;

				if (rxMail.Attachments.Count > 0)
					mail.MailAttachments = rxMail.Attachments;
				else if (rxMail.Entities[0].Attachments.Count > 0)
					mail.MailAttachments = rxMail.Entities[0].Attachments;
				else
					mail.MailAttachments = rxMail.Entities[1].Attachments;

				return mail;
		}

	}
}
